 package engine;

import engine.input.Inputs;
import engine.input.Keys;
import engine.render.RenderEngine;
import engine.res.Res;
import util.GLUtil;
import util.Timer;
import util.Util;

public abstract class EngineBase 
{

    protected static boolean running = true;
    
    public static void stopRunning() 
    {
        running = false;
    }
    
    protected boolean secSwitch;
    protected int fpsCounter;
    protected int secTick;
    protected int fpsTotal;
    protected int tick;
    protected float secCounter;
    protected float timeCycle;
    protected float timeTotal;
    protected float fpsInstant;
    private Timer timerCycle;
    private Timer timerSecond;
    private Timer timerTotal;
    protected Displays display;
    protected Prefs prefs;
    protected RenderEngine renderEngine;
    protected Inputs inputs;

    public EngineBase()
    {
        System.loadLibrary("lwjgl64");
        prefs = new Prefs();
    }
    
    public void run() throws Exception
    {
        display = new Displays(prefs);
        inputs = new Inputs(prefs);
        Res.loader().load();
        renderEngine = new RenderEngine(display);
        Util.consoleSysCapacity();
        GLUtil.consoleEngineCapacity();
        onStart();
        timerCycle = new Timer(true);
        timerSecond = new Timer(true);
        timerTotal = new Timer(true);
        while (running)
        {
            timeCycle = timerCycle.stopAndReturnTime();
            timerCycle.start();
            tick++;
            fpsInstant = 1.0f / timeCycle;
            secCounter = timerSecond.getTimePassed();
            timeTotal = timerTotal.getTimePassed();
            fpsCounter++;
            if (secCounter >= 1f) 
            {
                secTick++;
                timerSecond.moveBackBy(1f);
                fpsTotal = fpsCounter;
                fpsCounter = 0;
                secSwitch = !secSwitch;
                perSecond();
            }
            inputs.update();
            if (inputs.keys().isDown(Keys.ESCAPE) || display.isCloseRequested()) 
            {
                stopRunning();
            }
            onUpdate();
            renderEngine.priorToRender();
            renderEngine.render();
            display.updateScreen();
        }
        onClose();
        prefs.saveToFile();
        display.destroyDisplay();
        inputs.destroy();
    }

    protected void onStart() 
    {
    }

    protected void onUpdate() 
    {
    }

    protected void perSecond() 
    {
    }
    
    protected void onClose() 
    {
    }

}

/*
-Djava.library.path=F:\LWJGL\2.8.3\native\windows
-Djava.library.path=/Volumes/KINGSTON/LWJGL/2.8.3/native/macosx
-Djava.library.path=<lwjgl-X.X path>/native/<linux|macosx|solaris|windows>
*/